package com.jash.encryption;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * A simple {@link Fragment} subclass.
 */
public class SignFragment extends Fragment implements View.OnClickListener {

    private static final String PUB_STR = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDPWQMT9Iv4qShOv1DBLwwnFf03LYVgfInzNV7x" +
            "VqPzrXix14tgyi6Cx8IaOXNcFYRrDPkJ+HDd6Is8MvB7S6kVdw7emY30lsQr0HIl8RlSzrjRApcU" +
            "0p9zXzM2ssNrM2KI8poleXyVaEPItailrvP41J54ddrqPn7+RldUG/Qy/QIDAQAB";
    private static final String PRI_STR = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAM9ZAxP0i/ipKE6/UMEvDCcV/Tct\n" +
            "hWB8ifM1XvFWo/OteLHXi2DKLoLHwho5c1wVhGsM+Qn4cN3oizwy8HtLqRV3Dt6ZjfSWxCvQciXx" +
            "GVLOuNEClxTSn3NfMzayw2szYojymiV5fJVoQ8i1qKWu8/jUnnh12uo+fv5GV1Qb9DL9AgMBAAEC" +
            "gYA4MIcFAWBtImop7O6Va4p/jRXxvgRHAXjgz7XK8Q+9GWV7zE2ZDTFNf5S6RpdcfPhFil5ytUDg" +
            "4gPZbHR+9SH8kkeWd7b8QwaeCgfn5KFDG44lKB2OneuHByVo2OBFTaxJrPwqVwjIrn5WTPwBiaom" +
            "8QrxzkIYOYth5VaIiBPOgQJBAOecFle2CeSw4Ia5T5rfiDSf6PmJ9wMEm527cAeZsPub6S7pwGIo" +
            "J77kh4FDNo0CfwpEf3E/tfRN62UfvhmA03cCQQDlLtnLkQ5Mjm981hmAEYzWvC6/q+yFbRtKvpRq" +
            "dHpc4mypUB3Ht5qHmU308IaTPrpvr7nsVXXaDZ9Sy+mElEIrAkEAp3z/x0QUWXXzmFmwEH5vwCaX" +
            "0sULhPozEti2RjjFfN6dvVg60IDbZTdcKoURkN1qQ2GPi7UX/ujOPp262jSINwJAMbhqU7mSipVU" +
            "JpckTR6BmYyV78tSsteq1hpmhHnkmgYdYNYav9tbURO3T+5mo8c2F0jeYyFfQgE2kXXfoX2wpQJB" +
            "AMdtumn/j6AaWjUeSpbVBFm54EQ6x2d0l7W0MLbhwtT6INsIq1RllhFijbuAbhka9kp16htJlQTB" +
            "kdf3EnJfjG4=";
    private PublicKey publicKey;
    private PrivateKey privateKey;
    private TextInputLayout src;
    private TextInputLayout sign;

    public SignFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sign, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            KeyFactory factory = KeyFactory.getInstance("rsa");
            X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(PUB_STR, Base64.NO_WRAP));
            publicKey = factory.generatePublic(x509);
            PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(Base64.decode(PRI_STR, Base64.NO_WRAP));
            privateKey = factory.generatePrivate(pkcs8);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        src = ((TextInputLayout) view.findViewById(R.id.sign_src));
        sign = ((TextInputLayout) view.findViewById(R.id.sign_sign));
        view.findViewById(R.id.sign_commit).setOnClickListener(this);
        view.findViewById(R.id.sign_ver).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String src_str = src.getEditText().getText().toString();
        if (TextUtils.isEmpty(src_str)) {
            src.setError("不能为空");
            src.setErrorEnabled(true);
        } else {
            src.setErrorEnabled(false);
            try {
                Signature signature = Signature.getInstance("SHA256WithRSA");
                switch (view.getId()) {
                    case R.id.sign_commit:
                        signature.initSign(privateKey);
                        signature.update(src_str.getBytes());
                        byte[] bytes = signature.sign();
                        sign.getEditText().setText(Base64.encodeToString(bytes, Base64.NO_WRAP));
                        break;
                    case R.id.sign_ver:
                        String sign_str = sign.getEditText().getText().toString();
                        if (TextUtils.isEmpty(sign_str)) {
                            sign.setError("不能为空");
                            sign.setErrorEnabled(true);
                        } else {
                            sign.setErrorEnabled(false);
                            signature.initVerify(publicKey);
                            signature.update(src_str.getBytes());
                            if (signature.verify(Base64.decode(sign_str, Base64.NO_WRAP))) {
                                Toast.makeText(getContext(), "验证通过", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getContext(), "验证失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                        break;
                }
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (SignatureException e) {
                e.printStackTrace();
            }
        }
    }
}
